package com.allenkerr.service.impl;

import com.allenkerr.dao.ProductDao;
import com.allenkerr.service.ProductService;
import com.allenkerr.vo.ResultModel;
import org.apache.solr.client.solrj.SolrQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * Created by 小柯(Allen Kerr) on 17.5.2 9:31.
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Value("${pageSize}")
    private Integer pageSize;

    @Autowired
    private ProductDao productDao;

    @Override
    public ResultModel query(String queryString, String catalog_name, String price, String sort, Integer page)
            throws Exception {
        //创建查询条件对象
        SolrQuery solrQuery = new SolrQuery();

        //设置默认搜索域
        solrQuery.set("df", "product_keywords");

        //设置查询关键字
        if (queryString != null && !"".equals(queryString)) {
            solrQuery.setQuery(queryString);
        } else {
            solrQuery.setQuery("*:*");
        }

        //设置过滤条件，按照商品分类过滤
        if (catalog_name != null && !"".equals(catalog_name)) {
            solrQuery.addFilterQuery("product_catalog_name:" + catalog_name);
        }

        //设置过滤条件，按照价格过滤
        if (price != null && !"".equals(price)) {
            String[] split = price.split("-");
            if (split != null && split.length > 1) {
                solrQuery.addFilterQuery("product_price:[" + split[0] + " TO " + split[1] + "]");
            }
        }

        //设置排序方式
        if ("1".equals(sort)) {
            solrQuery.addSort("product_price", SolrQuery.ORDER.asc);
        } else {
            solrQuery.addSort("product_price", SolrQuery.ORDER.desc);
        }

        //设置分页，如果page为null，就将page设为1
        if (page == null || page < 1) {
            page = 1;
        }

        //从第几条开始查
        int start = (page - 1) * pageSize;
        solrQuery.setStart(start);

        //查询几条
        solrQuery.setRows(pageSize);

        //设置高亮
        solrQuery.setHighlight(true);

        //高亮的域
        solrQuery.addHighlightField("product_name");

        //高亮的前缀和后缀
        solrQuery.setHighlightSimplePre("<span style='color:red'>");
        solrQuery.setHighlightSimplePost("</span>");

        //调用productDao获取查询结果
        ResultModel resultModel = productDao.queryProducts(solrQuery);

        //设置当前页和总页数
        resultModel.setCurrPage(page);
        /**
         * 方法一：
         * int pageCount = (int) (resultModel.getRecordCount() % pageSize == 0 ?
                resultModel.getRecordCount() / pageSize : resultModel.getRecordCount() / pageSize + 1);
         * 方法二：
         * Math类 public static double ceil(double a)
         * 返回最小的（最接近负无穷大）double 值，该值大于等于参数，并等于某个整数。
         */
        int pageCount = (int) Math.ceil(resultModel.getRecordCount() * 1.0 / pageSize);
        resultModel.setPageCount(pageCount);

        //返回结果
        return resultModel;
    }
}
